package cn.miju.ser.common.rocketmq.consumer;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.miju.common.util.OkHttpUtil;
import cn.miju.database.constant.DbConstant;
import cn.miju.database.entity.Merchant;
import cn.miju.database.entity.RefundOrder;
import cn.miju.database.service.MerchantDataService;
import cn.miju.database.service.RefundOrderDataService;
import cn.miju.ser.common.rocketmq.Topic;
import cn.miju.ser.framework.request.MiJuPayRequest;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <pre>
 * 订单退款结果通知接入方
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-13 10:29
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = Topic.REFUND_RESULT_NOTIFY_TOPIC, consumerGroup = "${rocketmq.producer.group}")
public class RefundResultNotifyListener implements RocketMQListener<Long> {

    @Autowired
    private RefundOrderDataService refundOrderDataService;
    @Autowired
    private MerchantDataService merchantDataService;

    @Override
    public void onMessage(Long refundOrderId) {
        RefundOrder refundOrder = refundOrderDataService.getById(refundOrderId);
        if (Objects.nonNull(refundOrder)) {
            Merchant merchant = merchantDataService.getOne(new LambdaQueryWrapper<Merchant>().
                    select(Merchant::getPlatformMerchantNo, Merchant::getRefundNotifyUrl).
                    eq(Merchant::getId, refundOrder.getMerchantId()));
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("out_refund_no", refundOrder.getOutRefundNo());
            jsonParam.put("trade_no", merchant.isToMerchantTradeNo() ? refundOrder.getTradeNo() : refundOrder.getPlatRefundNo());
            jsonParam.put("total_amount", refundOrder.getRefundAmount());
            jsonParam.put("trade_status", DbConstant.RefundOrderStatus.SUCCESS.equals(refundOrder.getStatus()) ? "success" : "fail");
            jsonParam.put("refund_finish_time", refundOrder.getRefundTime() == null ? null : refundOrder.getRefundTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            // 向接入方发送订单支付成功通知
            MiJuPayRequest miJuPayRequest = new MiJuPayRequest();
            miJuPayRequest.setPlatformMerchantNo(merchant.getPlatformMerchantNo());
            miJuPayRequest.setTimeStamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            miJuPayRequest.setTransSerialNo(miJuPayRequest.getTimeStamp() + RandomUtil.randomInt(1000, 10000));
            miJuPayRequest.setEncrypt(false);
            miJuPayRequest.setBizContent(jsonParam.toString());
            JSONObject signJson = JSONObject.parseObject(JSONObject.toJSONString(miJuPayRequest));
            String sign = SecureUtil.md5(signJson.toString());
            miJuPayRequest.setSign(sign);
            OkHttpUtil.doPostJson(merchant.getRefundNotifyUrl(), JSONObject.toJSONString(miJuPayRequest));
        }
    }
}
